package Login;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import Utils.Constant;
import Utils.DbAccess;
import Utils.MD5;
import Utils.ZipResponse;



public class DoChangePassword extends HttpServlet {

	private static final long serialVersionUID = 1L;
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
		throws ServletException, IOException {
		proccess(req, resp);
	}
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
		throws ServletException, IOException {
	
		proccess(req, resp);
	}
	
	private void proccess(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
		req.setCharacterEncoding("UTF-8");
		res.setCharacterEncoding("UTF-8");
		res.setContentType("text/xml");
		String 	xml = "<xml value='false'/>";
		String password="",old_pass="";
		if(!CheckLogin.check(req)){
			ZipResponse.write(req, res, "<root value='notlogin'/>", "UTF-8");
			return;
		}
		
		
		try{
			password = MD5.encrypt(req.getParameter("password"));
			old_pass = MD5.encrypt(req.getParameter("oldpass"));
		}
		catch (Exception e) {
			ZipResponse.write(req, res, xml, "UTF-8");
			return;
		}
		
		DbAccess db = null;
		
		try{
			db = new DbAccess();
			db.connectTemp("localhost", Constant.DB);
			HttpSession session = req.getSession();
			String username =(String) session.getAttribute("userid");
			String sql = "Update account set password=? where username = '"+username+"' and password=?";
			db.stmt = db.conn.prepareStatement(sql);
			db.stmt.setString(1, password);
			db.stmt.setString(2, old_pass);
			db.stmt.executeUpdate();
			xml = "<root value='true'/>";
			
		}catch (SQLException e) {
			xml = "<root value='false'/>";
			e.printStackTrace();
		}finally{
			db.DBClose();
		}
		
		ZipResponse.write(req, res, xml, "UTF-8");
	
	}
}
